<template>
  <div class="divCheckListAdd box contenBox">
    <div class="divSteps">
      <el-steps :active="activeStep" finish-status="success">
        <el-step title="填写基础信息"></el-step>
        <el-step title="填写盘点清单"></el-step>
      </el-steps>
    </div>
    <div class="divForm" v-if="activeStep === 0">
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        v-loading="loading"
      >
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="盘点单号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入"
                clearable
                disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点原因" prop="reason">
              <el-select
                  v-model="form.reason"
                clearable
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="item in checkReasonOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点维度" prop="dimension">
              <el-select
              v-model="form.dimension"
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in checkDimensionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点类型" prop="type">
            <el-select
              v-model="form.type"
              clearable
              placeholder="请选择"
                style="width:100%"
            >
              <el-option
                v-for="item in checkTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6" v-if="form.dimension !== 'HP'">
            <el-form-item label="库区" prop="location" class="labelArea">
              <el-cascader  v-model="form.location"
                            @change="handleItemChange"
                            :props="cascaderOptions.props"
                            clearable
                            style="width:100%"
                            v-if="cascaderOptionsFlag"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.dimension !== 'KW'">
            <el-form-item label="货主" prop="ownerId" class="labelOwner">
              <el-select
              v-model="form.ownerId"
              clearable
              placeholder="请选择"
                style="width:100%"
            >
              <el-option
                v-for="item in ownerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划时间" prop="planCheckTime">
            <el-date-picker
              v-model="form.planCheckTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              prefix-icon="el-icon-date"
              clearable
              style="width:100%"
              :picker-options="pickerOptions"
              placeholder="选择日期时间">
            </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="buttonBox" v-if="activeStep === 0">
      <base-button
        class="unimportanceButton"
        @click="btnReturnClick"
      >返回</base-button>
      <base-button
        class="minorImportantButton"
        @click="btnNextStepClick"
      >下一步</base-button>
    </div>
    <component-check-list :ownerId="form.ownerId" :dimension="form.dimension"  :areaId="form.areaId" :masterId="masterId" v-else></component-check-list>
  </div>
</template>

<script lang="ts">
import BaseButton from '@/components/base-button/index.vue'
import { Component } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import SinglePage from '@/mixin/single-page'
import { getAllWarehouse } from '@/module-base/api/warehouse'
import { IWarehouseTableData } from '@/module-base/interface/warehouse'
import { getAllAreaList } from '@/module-base/api/area'
import { IAreaTableData } from '@/module-base/interface/area'
import { checkStatusOptions, checkTypeOptions, checkReasonOptions, checkDimensionOptions } from '@/utils/common-select-data'
import { ICommonReturn, ICommonSelectOptions, ICommonSelectOptionsString } from '@/utils/common-interface'
import { getAllOwner } from '@/module-business/api/owner'
import { IOwnerTableData } from '@/module-business/interface/owner'
import { generateWarehouseCode } from '@/api/common-api'
import { addCheck, getCheck, updateCheck } from '@/module-storage/api/check'
import { ElForm } from 'element-ui/types/form'
import ComponentCheckList from './components/component-check-list.vue'
@Component({
  name: 'CheckListAdd',
  components: {
    BaseButton,
    ComponentCheckList
  }
})
export default class extends mixins(SinglePage) {
  private form = {
    code: '',
    reason: '',
    dimension: '',
    type: '',
    location: [],
    ownerId: null,
    planCheckTime: '',
    areaId: null,
    status: 0,
    id: ''
  }

  private checkStatusOptions:ICommonSelectOptions[] = []

  private checkTypeOptions :ICommonSelectOptionsString[] = []

  private checkReasonOptions :ICommonSelectOptionsString[] = []

  private checkDimensionOptions : ICommonSelectOptionsString[] = []

  private ownerOptions :ICommonSelectOptions[] = []

  private activeStep = 0// 2表示流程结束

  private loading = false

  private cascaderOptions = {
    props: {
      lazy: true,
      lazyLoad: async(node:any, resolve:any) => {
        const { level } = node
        if (level === 0) {
          const { data } = await getAllWarehouse({ status: 1 })
          const nodes = data.map((item:IWarehouseTableData) => {
            return {
              value: item.id,
              label: item.name,
              leaf: level >= 1 // 不设置的话点击第一级菜单也会触发change事件  文本区域也会填充
            }
          })
          resolve(nodes)
        } else if (level === 1) {
          const { data } = await getAllAreaList({ warehouseId: node.value })
          let nodes = []
          if (data) {
            nodes = data.map((item:IAreaTableData) => {
              return {
                value: item.id,
                label: item.name,
                leaf: level >= 1// 不设置的话还会继续加载下一级菜单
              }
            })
          }
          resolve(nodes)
        }
      }
    }
  }

  private cascaderOptionsFlag = false

  private rules = {
    reason: [{ required: true, message: '请选择盘点原因', trigger: 'change' }],
    dimension: [{ required: true, message: '请选择盘点原因', trigger: 'change' }],
    type: [{ required: true, message: '请选择盘点原因', trigger: 'change' }],
    // location: [{ required: true, message: '请选择库区', trigger: 'change' }],
    // ownerId: [{ required: true, message: '请选择货主', trigger: 'change' }],
    planCheckTime: [{ required: true, message: '请选择盘点原因', trigger: 'change' }]
  }

  private masterId = ''

  private pickerOptions = {
    disabledDate(time:Date) {
      return time.getTime() < Date.now()
    }
  }

  private map:Map<string, string> = new Map()

  created() {
    this.initData()
  }

  private async initData() {
    this.loading = true
    this.checkStatusOptions = checkStatusOptions
    this.checkTypeOptions = checkTypeOptions
    this.checkReasonOptions = checkReasonOptions
    this.checkDimensionOptions = checkDimensionOptions
    this.getOwnerOptions()
    const id = this.$route.params.id
    if (id === 'null') {
    // 新增操作
      const { data } = await generateWarehouseCode('PD')
      this.form.code = data
    } else {
    // 修改操作
      this.masterId = id
      const { data } = await getCheck(id)
      this.form = {
        ...data,
        location: [data.warehouseId, data.areaId]
      }
    }
    this.cascaderOptionsFlag = true
    this.loading = false
    this.map.set(this.form.dimension, this.form.dimension)
  }

  private async getOwnerOptions() {
    const { data } = await getAllOwner(null)
    this.ownerOptions = data.map((item:IOwnerTableData) => {
      return {
        label: item.name,
        value: item.id
      }
    })
  }

  private handleItemChange(value:string) {
    if (Array.isArray(value) && value.length === 2) {
      this.form.areaId = value[1]
    }
  }

  private btnReturnClick() {
    this.$router.go(-1)
  }

  private btnNextStepClick() {
    (this.$refs.ruleForm as ElForm).validate(async(valid: boolean) => {
      if (valid) {
        if (this.form.status === 0) {
          this.form.status = 1
        }
        const form = this.form
        // 如果盘点维度是货品的话货主是必选项
        if (form.dimension === 'HP') {
          form.location = []
          if (!form.ownerId) {
            this.$message.error('请选择货主')
            return
          }
        }
        // 如果盘点维度是库位的话库区是必选项
        if (form.dimension === 'KW') {
          form.ownerId = null
          if (form.location && form.location.length !== 2) {
            this.$message.error('请选择库区')
            return
          }
        }

        const params = {
          ...form,
          warehouseId: form.location[0],
          areaId: form.location[1],
          location: undefined
        }
        let data: ICommonReturn
        if (!this.masterId) {
          // 新增操作
          data = ((await addCheck(params)) as unknown) as ICommonReturn
        } else {
          data = ((await updateCheck(params)) as unknown) as ICommonReturn
        }
        if (data.code === 0) {
          this.$message({
            showClose: true,
            message: '恭喜你，提交成功！',
            type: 'success'
          })
          this.activeStep = 1
          this.masterId = (data.data as any).id// 新增或者修改之后返回的记录的id
          this.form.id = (data.data as any).id
          this.map.set(form.dimension, form.dimension)
        } else {
          this.$message({
            showClose: true,
            message: data.msg,
            type: 'error'
          })
        }
      } else {
        return false
      }
    })
  }

  // 从填写盘点清单到填写基础信息
  private btnReturn() {
    this.activeStep = 0
  }
}

</script>

<style lang="scss" scoped>
  .divCheckListAdd{
      .divSteps{
        width: 440px;
        margin: 0 auto;
        height: 100px;
        margin-top: 56px;
      }
  }

  ::v-deep .labelArea{
          .el-form-item__label:before{
            content: "*";
            color: #d9021c;
            margin-right: 4px;

          }
  }
    ::v-deep .labelOwner{
          .el-form-item__label:before{
            content: "*";
            color: #d9021c;
            margin-right: 4px;

          }
  }
</style>
